//
//  PhotoPageViewController.m
//  SecretAlbums
//
//  Created by BabyFinancial on 15/6/25.
//  Copyright (c) 2015年 BabyFinancial. All rights reserved.
//

#import "AssetPageViewController.h"
#import "AssetItemViewController.h"
#import "SecretAlbumsLogic.h"
#import <MediaPlayer/MediaPlayer.h>
#import "Masonry.h"
#import "PagePromptView.h"
#import "SecretAlbumsConst.h"
#import "ConfirmViewController.h"
#import "UIView+SecretAlbums.h"
#import "AppDelegate.h"

@interface AssetPageViewController () <UIPageViewControllerDataSource, UIPageViewControllerDelegate, AssetItemViewControllerDataSource, AssetItemViewControllerDelegate, ConfirmViewControllerDelegate>

@property (nonatomic, strong) NSArray *medias;
@property (nonatomic, strong) NSOperationQueue *queue;
@property (nonatomic, strong) MPMoviePlayerController *player;
@property (nonatomic, weak) AssetItemViewController *playVideoViewController;
@property (nonatomic, assign) BOOL isReadyRotate;
@property (nonatomic, strong) PagePromptView *pagePromptView;
@property (nonatomic, strong) ConfirmViewController *confirmViewController;

@end

@implementation AssetPageViewController

- (id)initWithMedias:(NSArray *)medias
{
    self = [super initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll
                    navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal
                                  options:@{UIPageViewControllerOptionInterPageSpacingKey:@30.f}];
    
    if (self) {
        self.medias                 = medias;
        self.dataSource             = self;
        self.delegate               = self;
        self.view.backgroundColor   = [UIColor blackColor];
        self.queue = [[NSOperationQueue alloc] init];
        [self.queue setMaxConcurrentOperationCount:1];
    }
    
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // 添加标记页数View
    self.pagePromptView = [[PagePromptView alloc] init];
    [self.pagePromptView setTranslatesAutoresizingMaskIntoConstraints:NO];
    [self.view addSubview:self.pagePromptView];
}

- (void)dealloc
{
    [self removeNotificationObserver];
    [self removeNotificationObserverOfApplication];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationFade];
    [self addNotificationObserverOfApplication];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.isReadyRotate = YES;
}

- (MPMoviePlayerController *)player
{
    if (!_player) {
        _player = [MPMoviePlayerController new];
        [self addNotificationObserver];
    }
    
    return _player;
}

- (BOOL)shouldAutorotate
{
    return self.isReadyRotate;
}

- (NSUInteger)supportedInterfaceOrientations
{
    return self.isReadyRotate ? UIInterfaceOrientationMaskAllButUpsideDown : UIInterfaceOrientationMaskPortrait;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationPortrait;
}

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
    AssetItemViewController *controller = (AssetItemViewController *)self.viewControllers.firstObject;
    [controller.view setUserInteractionEnabled:NO];
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
    AssetItemViewController *controller = (AssetItemViewController *)self.viewControllers.firstObject;
    [controller.view setUserInteractionEnabled:YES];
}

#pragma mark - Page Index

- (NSInteger)pageIndex
{
    return ((AssetItemViewController *)self.viewControllers.firstObject).pageIndex;
}

- (void)setPageIndex:(NSInteger)pageIndex
{
    // 更新index提示
    NSInteger count = self.medias.count;
    [self setupPagePromptTitleAndLayoutWithPageIndex:pageIndex+1 Count:count];
    
    if (pageIndex >= 0 && pageIndex < count) {
        AssetItemViewController *itemController = [AssetItemViewController assetItemViewControllerForPageIndex:pageIndex];
        itemController.dataSource = self;
        itemController.delegate = self;
        
        [self setViewControllers:@[itemController]
                       direction:UIPageViewControllerNavigationDirectionForward
                        animated:NO
                      completion:NULL];
        
        Media *media = self.medias[pageIndex];
        if (!media.isVideo.boolValue) {
            NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(loadFullResolutionImage:) object:itemController];
            [self.queue addOperation:operation];
        } else {
            [self loadVideoPlayer:media ViewController:itemController];
        }
    }
}

#pragma mark - 私有方法

- (void)openConfirmView
{
    if (!self.confirmViewController) {
        self.confirmViewController = [ConfirmViewController new];
        self.confirmViewController.delegate = self;
    }
    
    [self.confirmViewController setupBackgroundWithImage:[self.view currentScreenImg]];
    
    [self addChildViewController:self.confirmViewController];
    [self.view addSubview:self.confirmViewController.view];
    [self.confirmViewController didMoveToParentViewController:self];
    
    [self.confirmViewController.view setTranslatesAutoresizingMaskIntoConstraints:NO];
    [self.confirmViewController.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
    if (UIInterfaceOrientationLandscapeLeft == orientation) {
        [self.confirmViewController.numberpadView setTransform:CGAffineTransformMakeRotation(90*M_PI / 180.0)];
    } else if (UIInterfaceOrientationLandscapeRight == orientation) {
        [self.confirmViewController.numberpadView setTransform:CGAffineTransformMakeRotation(-90*M_PI / 180.0)];
    } else {
        [self.confirmViewController.numberpadView setTransform:CGAffineTransformMakeRotation(0*M_PI / 180.0)];
    }
    
    self.isReadyRotate = NO;
}

- (void)dismissConfirmView
{
    self.isReadyRotate = YES;
    
    [self.confirmViewController willMoveToParentViewController:nil];
    [self.confirmViewController.view removeFromSuperview];
    [self.confirmViewController removeFromParentViewController];
}

- (void)applicationDidEnterBackground:(NSNotification *)notification
{
    [self openConfirmView];
}

- (void)setupPagePromptTitleAndLayoutWithPageIndex:(NSInteger)pageIndex Count:(NSInteger)count
{
    NSString *title = [NSString stringWithFormat:@"%ld/%ld", pageIndex, count];
    self.pagePromptView.titleLabel.text = title;
    
    NSDictionary *dic = @{NSFontAttributeName : self.pagePromptView.titleLabel.font};
    CGRect rect = [title boundingRectWithSize:self.view.bounds.size
                                      options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                   attributes:dic
                                      context:nil];
    
    [self.pagePromptView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGRectInset(rect, -10, -2).size);
        make.centerX.equalTo(self.view.mas_centerX);
        make.top.equalTo(self.view.mas_top).offset(20.0f);
    }];
}

/** 注册播放视频消息 */
- (void)addNotificationObserver
{
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    
    [center addObserver:self
               selector:@selector(playbackStateDidChange:)
                   name:MPMoviePlayerPlaybackStateDidChangeNotification
                 object:nil];
    
    [center addObserver:self
               selector:@selector(playbackDidFinish:)
                   name:MPMoviePlayerPlaybackDidFinishNotification
                 object:nil];
}

/** 注销播放视频消息 */
- (void)removeNotificationObserver
{
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    
    [center removeObserver:self name:MPMoviePlayerPlaybackStateDidChangeNotification object:nil];
    [center removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
}

/** 注册程序进入，退出前台响应消息 */
- (void)addNotificationObserverOfApplication
{
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    
    [center addObserver:self
               selector:@selector(applicationDidEnterBackground:)
                   name:UIApplicationDidEnterBackgroundNotification
                 object:nil];
}

/** 注销程序进入，退出前台响应消息 */
- (void)removeNotificationObserverOfApplication
{
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    
    [center removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];
}

/** 加载媒体信息，在副线程中调用 */
- (void)loadFullResolutionImage:(AssetItemViewController *)item
{
    if (item.pageIndex != self.pageIndex) return;
    
    // 媒体信息存储地址
    Media *media = [self.medias objectAtIndex:item.pageIndex];
    UIImage *img = [UIImage imageWithContentsOfFile:[SecretAlbumsLogic pathWithMediaType:MediaTypeMedia name:media.fileName]];
    
    if (item.pageIndex == self.pageIndex) {
        // 还在当前页面才切换
        [item performSelectorOnMainThread:@selector(setFullResolutionImage:) withObject:img waitUntilDone:NO];
    }
}

#pragma mark - UIPageViewControllerDataSource

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(UIViewController *)viewController
{
    NSInteger index = ((AssetItemViewController *)viewController).pageIndex;
    
    if (index > 0) {
        AssetItemViewController *itemController = [AssetItemViewController assetItemViewControllerForPageIndex:(index - 1)];
        itemController.dataSource = self;
        itemController.delegate = self;
        
        return itemController;
    }
    
    return nil;
}

- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(UIViewController *)viewController
{
    NSInteger count = self.medias.count;
    NSInteger index = ((AssetItemViewController *)viewController).pageIndex;
    
    if (index < count - 1) {
        AssetItemViewController *itemController = [AssetItemViewController assetItemViewControllerForPageIndex:(index + 1)];
        itemController.dataSource = self;
        itemController.delegate = self;
        
        return itemController;
    }
    
    return nil;
}

- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray *)previousViewControllers transitionCompleted:(BOOL)completed
{
    if (completed) {
        // 更新index提示
        [self setupPagePromptTitleAndLayoutWithPageIndex:self.pageIndex+1 Count:self.medias.count];
        
        // 多线程加载图片处理
        [self.queue cancelAllOperations];
        [self.player stop];
        [self.player.view removeFromSuperview];
        
        AssetItemViewController *itemController = (AssetItemViewController *)pageViewController.viewControllers.firstObject;
        
        Media *media = self.medias[itemController.pageIndex];
        if (!media.isVideo.boolValue) {
            NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(loadFullResolutionImage:) object:itemController];
            [self.queue addOperation:operation];
        } else {
            [self loadVideoPlayer:media ViewController:itemController];
        }
    }
}

- (void)loadVideoPlayer:(Media *)media ViewController:(AssetItemViewController *)itemController
{
    NSURL *url = [NSURL fileURLWithPath:[SecretAlbumsLogic pathWithMediaType:MediaTypeMedia name:media.fileName]];
    
    self.player.contentURL = url;
    [self.player.view setHidden:YES];
    self.player.controlStyle = MPMovieControlStyleNone;
    [self.player setShouldAutoplay:NO];
    [self.player prepareToPlay];
    [self.player.view setTranslatesAutoresizingMaskIntoConstraints:NO];
    
    self.player.view.frame = itemController.view.bounds;
    [itemController.view insertSubview:self.player.view belowSubview:[itemController imageViewInAssetView]];
    [self.player.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(itemController.view);
    }];
}

- (void)playbackStateDidChange:(NSNotification *)notification
{
    switch (self.player.playbackState) {
        case MPMoviePlaybackStatePlaying: {
            if (self.playVideoViewController) {
                [self.playVideoViewController setVideoState:PlayVideoStatePlaying];
            }
            break;
        } default:
            break;
    }
}

- (void)playbackDidFinish:(NSNotification *)notification
{
    [self.player stop];
    
    if (self.playVideoViewController) {
        Media *media = self.medias[self.playVideoViewController.pageIndex];
        NSURL *url = [NSURL fileURLWithPath:[SecretAlbumsLogic pathWithMediaType:MediaTypeMedia name:media.fileName]];
        
        self.player.contentURL = url;
        [self.player setShouldAutoplay:NO];
        [self.player prepareToPlay];
        
        [self.playVideoViewController setVideoState:PlayVideoStateFinished];
    }
}

#pragma mark - AssetItemViewControllerDataSource

- (Media *)mediaAtIndex:(NSUInteger)index
{
    return [self.medias objectAtIndex:index];
}

#pragma mark - AssetItemViewControllerDelegate

- (void)playVideo:(AssetItemViewController *)assetItemViewController
{
    self.playVideoViewController = assetItemViewController;
    [self.player play];
}

- (MPMoviePlayerController *)playerController
{
    return self.player;
}

- (void)longPress:(AssetItemViewController *)assetItemViewController
{
    [self.pagePromptView setHidden:!self.pagePromptView.hidden];
}

#pragma mark - ConfirmViewControllerDelegate

- (void)successConfirmViewController:(ConfirmViewController *)confirmViewController
{
    [self dismissConfirmView];
}

@end
